package com.audaque.springboot.foshanupload.web.nosaveframeworkloginvalid.interceptor;


import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.authcore.anno.NeedLoginAnno;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;

import com.audaque.springboot.foshanupload.authcore.properties.LoginProperties;
import com.audaque.springboot.foshanupload.core.properties.StaticResourcePathProperties;
import com.audaque.springboot.foshanupload.core.properties.SwitchProperties;
import com.audaque.springboot.foshanupload.jwtcore.properties.JwtProperties;
import com.audaque.springboot.foshanupload.core.result.R;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author zgb
 * @desc 检查是否已登录
 * @date 2022-06-16 18:37:27
 */
//通过配置order()的值，值越小，优先级越高。不配默认是0
@Order(100)
@Slf4j
public class NeedLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private SwitchProperties switchProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private LoginProperties loginProperties;
    @Autowired
    private StaticResourcePathProperties staticResourcePathProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        //要排除的路径
        List<String> excludePathPatterns = staticResourcePathProperties.getList();
        List<String> unAuthenticatedUrlList = loginProperties.getUnAuthenticatedUrlList();

        unAuthenticatedUrlList.addAll(excludePathPatterns);


        String excludedUris = String.join(",", unAuthenticatedUrlList);
        String[] excludedUriArr = excludedUris.split(",");

        String url = request.getRequestURI().toString();

        log.debug("url：" + url);

        // 定义表示变量 并验证用户请求URI 是否包含不过滤路径
        boolean flag = false;
        for (String uri : excludedUriArr) {

            if (url.equals(uri)) {
                flag = true;
            }
        }
        if (flag) {
            //放行
            return true;
        }




        boolean existYn = false;
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();

            if (clazz.isAnnotationPresent(NeedLoginAnno.class)) {
                existYn = true;
            } else if (method.isAnnotationPresent(NeedLoginAnno.class)) {
                existYn = true;
            }
        }

        if (!existYn) {
            return true;
        }
        TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = TransmittableThreadLocalCurrentUser.getCurrentUser();

        if (transmittableThreadLocalCurrentUser != null) {
            return true;
        }

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");



        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCodeEnum.NOT_LOGIN.getCode());
        r.setMsg(ResultCodeEnum.NOT_LOGIN.getMsg());
        response.getWriter().write(JSONUtil.toJsonStr(r));
        return false;
    }
}
